package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.CurrentUserHolder;
import com.nineclock.system.mapper.SysCompanyUserMapper;
import com.nineclock.system.pojo.SysCompanyUser;
import com.nineclock.system.service.SysCompanyUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Slf4j
@Service
public class SysCompanyUserServiceImpl extends ServiceImpl<SysCompanyUserMapper, SysCompanyUser> implements SysCompanyUserService {

    @Autowired
    private SysCompanyUserMapper sysCompanyUserMapper;

    /**
     * 思路：
     * 1.获取当前登录用户的公司ID
     * 2.根据公司ID查询到主用户
     * 3.如果判断为空则抛异常
     * 4.响应数据
     */
    @Override
    public SysCompanyUser findCurrentAdmin() {

        //获取登录用户的公司ID
        Long companyId = CurrentUserHolder.get().getCompanyId();

        //查询主管理员
        SysCompanyUser sysCompanyUser = sysCompanyUserMapper.findCurrentAdmin(companyId);

        //判断是否为空
        if(sysCompanyUser==null){
            throw new NcException(ResponseEnum.COMPANY_ADMIN_NOT_EXISTS);
        }

        //响应数据
        return sysCompanyUser;
    }


    @Override
    public List<SysCompanyUser> findAllUser() {

        //1.获取当前登录用户的公司ID
        Long companyId = CurrentUserHolder.get().getCompanyId();

        //2.查询公司下的所有员工，状态可用
        LambdaQueryWrapper<SysCompanyUser> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(SysCompanyUser::getCompanyId, companyId);
        lambdaQueryWrapper.eq(SysCompanyUser::getEnable,1);

        //3.查询数据列表
        List<SysCompanyUser> sysCompanyUserList = this.list(lambdaQueryWrapper);

        //4.判断数据如果不存在就抛异常
        if(CollectionUtil.isEmpty(sysCompanyUserList)){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }

        //5.响应数据
        return sysCompanyUserList;
    }

}
